//
//  FeedbackViewController.m
//  HTT
//
//  Created by 王鑫 on 15/12/2.
//  Copyright © 2015年 nit. All rights reserved.
//

#import "FeedbackViewController.h"

//textView
#import "PlaceholderTextView.h"

//ViewModel
#import "FeedbackViewModel.h"

#define MAX_LIMIT_NUMS 150
#define CELLH 28
@interface FeedbackViewController () <UITextViewDelegate>

@property (nonatomic, strong) PlaceholderTextView *feedbackTextView;

@property (nonatomic, strong) UILabel *textNumLabel;

@property int count;

@end

@implementation FeedbackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self initNav];
}

//TODO: 导航栏初始化
- (void)initNav {
    [self addCustomBackBase];
    [self addCustomTitleWithTitle:@"反馈信息"];
}

//TODO: 绘制UI
- (void)initUI {
    self.view.backgroundColor = RGBCOLOR(233.0, 233.0, 233.0, 1);
    _feedbackTextView = [[PlaceholderTextView alloc] initWithFrame:CGRectMake(21, 17, ScreenWidth - 42, ScreenWidth - 32)];
    _feedbackTextView.placeholder = @"请输入您的意见(150字以内)";
    _feedbackTextView.placeholderFont = [UIFont systemFontOfSize:17];
    _feedbackTextView.font = [UIFont systemFontOfSize:17];
    _feedbackTextView.backgroundColor = [UIColor clearColor];
    _feedbackTextView.delegate = self;
    UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake(14, 10, ScreenWidth - 28, ScreenWidth  - 40)];
    view.image = [UIImage imageNamed:@"Feedback_bg_input"];
    [self.view addSubview:view];
    [self.view addSubview:_feedbackTextView];
    
    float h;
    float cellH = CELLH;
    float curHeight = ScreenWidth - 54;
    for (h = cellH ; h < (curHeight - cellH); h += cellH - 7.8)
    {
        
        UIImageView *lineView = [[UIImageView alloc] initWithFrame:CGRectMake(4, h,_feedbackTextView.frame.size.width - 8, 1)];
        lineView.image = [UIImage imageNamed:@"feedback_line"];
        [_feedbackTextView addSubview:lineView];
    }
    _textNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(7, ScreenWidth - 78, ScreenWidth - 42, 30)];
    _textNumLabel.textColor = _feedbackTextView.placeholderColor;
    _textNumLabel.textAlignment = _TEXT_ALIGN_RIGHT;
    _textNumLabel.font = [UIFont systemFontOfSize:17];
    _textNumLabel.text = @"0/150";
    [view addSubview:_textNumLabel];
    
    UIButton *sendButton = [[UIButton alloc] initWithFrame:CGRectMake(14, ScreenWidth + 10, ScreenWidth - 28, 34)];
    sendButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_selected"]];
    [sendButton setTitle:@"确认" forState:UIControlStateNormal];
    sendButton.layer.cornerRadius = 5;
    [sendButton addTarget:self action:@selector(sendFeedbackInfo) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendButton];
}
//TODO: UItextView代理
-(void)textViewDidChange:(UITextView *)textView
{
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    //如果在变化中是高亮部分在变，就不计算字符
    if (selectedRange && pos) {
        return;
    }
    
    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;
    
    if (existTextNum > MAX_LIMIT_NUMS)
    {
        //截取到最大位置的字符
        NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];
        
        self.textNumLabel.text = [NSString stringWithFormat:@"%d/%d",MAX_LIMIT_NUMS,MAX_LIMIT_NUMS];
        [self showSVProgressFailed:@"已达到上限"];
        [textView setText:s];
    }else {
        self.textNumLabel.text = [NSString stringWithFormat:@"%ld/%d",existTextNum,MAX_LIMIT_NUMS];
    }
    
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    //如果有高亮且当前字数开始位置小于最大限制时允许输入
    if (selectedRange && pos) {
        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
        
        if (offsetRange.location < MAX_LIMIT_NUMS) {
            return YES;
        }
        else
        {
            return NO;
        }
    }
    
    
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;
    if (caninputlen >= 0)
    {
        return YES;
    }
    else
    {
        NSInteger len = text.length + caninputlen;
        
        NSRange rg = {0,MAX(len,0)};
        
        if (rg.length > 0)
        {
            NSString *s = [text substringWithRange:rg];
            
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
            self.textNumLabel.text = [NSString stringWithFormat:@"%d/%ld",0,(long)MAX_LIMIT_NUMS];
        }
        return NO;
    }
    
}

//TODO: 发送反馈信息
/** 发送反馈信息
 *
 *  @param phoneNumber
 *  @param feedbackInfo
 **/
- (void)sendFeedbackInfo {
    FeedbackViewModel *feedbackVM = [[FeedbackViewModel alloc] init];
    [feedbackVM setBlockWithReturnBlock:^(id returnValue) {
        [self hiddenMbProgress];
        if ([(NSDictionary *)returnValue[INTERFACE_RESULT] isEqual:INTERFACE_SUCCESS]) {
            [self showSVProgressSuccess:@"发送成功"];
        }else
            [self showSVProgressFailed:@"发送失败"];
    } WithErrorBlock:^(id errorCode) {
        [self hiddenMbProgress];
        [self showSVProgressFailed:@"发送失败"];
    } WithFailureBlock:^{
        [self hiddenMbProgress];
        [self showSVProgressFailed:@"网络错误"];
    }];
    [self showMbProgress:@""];
    [feedbackVM addValidatecodeSmsInfoByPhoneNumber:[USERCONTENT getUserLoginName] andSmsContent:_feedbackTextView.text];
}

#pragma mark 解决键盘挡住UITextView的方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
